
import { get } from 'lodash-es'
import classnames from 'classnames'
import React, { useState } from 'react';
import { SegmentedControl, SegmentedControlItem } from '@mantine/core'

interface ITabsProps { 
  data: (string | SegmentedControlItem)[],
  children?: React.ReactElement[];
}

interface ITabItemProps {
  value: string
  children?: React.ReactNode;
  className?: string
  show?: boolean
}

export function ITabs(props: ITabsProps) {
  const {
    data,
    children
  } = props;
  const [tabKey, setTabKey] = useState<string>(getDefaultTabKey());

  function getDefaultTabKey() {
    const dataItem = get(data, '[0]');
    return typeof dataItem === 'string' ? dataItem : dataItem.value;
  }

  function onTabChange(key: string) {
    setTabKey(key)
  }

  function renderChildren() {
    if (!children) return null;

    return children.map((child, index) => {
      return React.cloneElement(child, {
        key: index,
        ...child.props,
        show: child.props.value === tabKey
      })
    })
  } 

  return (
    <div className='w-full h-auto'>
      <div className='w-full p-2'>
        <SegmentedControl className='w-full' data={data} onChange={onTabChange}  />
      </div>
      <div>
        { renderChildren() }
      </div>
    </div>
  )
}

export function ITabItem(props: ITabItemProps) {
  const {
    children,
    className,
    show = false
  } = props;

  if (!show) return null;

  return (
    <div className={classnames('p-2', className)}>
      { children }
    </div>
  )
}